package group.sicher.lock.brain.lock;

import group.sicher.lock.Exception.MarsKeyBuilderException;
import group.sicher.lock.annotation.MarsKey;
import group.sicher.lock.brain.MarsLockKey;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @description: 方法上的锁注解
 * @author: aron
 * @date: 2019-08-05 16:59
 */
@Slf4j
public class MarsKeyMethodLock extends MarsKeyLockAbstractor {

    public MarsKeyMethodLock(String className, String methodName, Method realMethod, Object[] args) {
        super(className, methodName, realMethod, args);
    }

    @Override
    public MarsLockKey.Builder builder() throws MarsKeyBuilderException {

        MarsLockKey.Builder keyBuilder = MarsLockKey.instance();
        String[] values = realMethod.getAnnotation(MarsKey.class).value();
        for (int i = 0; i < args.length; i++) {
            Object obj = args[i];
            Class objectClass = obj.getClass();
            Field[] fields = objectClass.getDeclaredFields();
            for (String value : values) {
                String[] propertyName = value.split("\\.");
                String[] className = objectClass.getName().split("\\.");
                if (propertyName[0].equals(className[className.length - 1])) {
                    for (Field field : fields) {
                        field.setAccessible(true);
                        if (field.getName().equals(propertyName[1])) {
                            try {
                                keyBuilder.setKey(wrapKeyTag(field.get(obj).toString()));
                            } catch (IllegalAccessException e) {
                                log.error(e.getMessage(), e);
                                throw new MarsKeyBuilderException("生成builder失败", e);
                            }
                        }
                    }
                }
            }
        }
        return keyBuilder;
    }
}
